import {
  ExceptionFilter,
  ArgumentsHost,
  Catch,
  HttpException,
  BadRequestException,
} from '@nestjs/common';
import { Response } from 'express';
import { I18nService, I18nValidationException } from 'nestjs-i18n';

@Catch(HttpException)
export class AdminExceptionFilter implements ExceptionFilter {
  constructor(private readonly i18n: I18nService) {}
  catch(exception: any, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const request: any = ctx.getRequest<Request>();
    const response = ctx.getResponse<Response>();
    let status = exception.getStatus();
    let errorMessage = exception.message;
    if (exception instanceof BadRequestException) {
      const expectionBody = exception.getResponse();
      if (
        typeof expectionBody === 'object' &&
        expectionBody.hasOwnProperty('message')
      ) {
        errorMessage = expectionBody['message'];
        status = expectionBody['statusCode'];
      }
    } else if (exception instanceof I18nValidationException) {
      const errors = exception.errors;
      errorMessage = errors
        .map((error) => this.formatErrorMessage(error, request.i18nLang))
        .join(';');
    }
    response.status(status).render('error', {
      message: errorMessage,
    });
  }
  formatErrorMessage(error, lang) {
    const { property, constraints, value } = error;
    const formattedMessage = Object.values(constraints).map(
      (constraintValue: string) => {
        const [key, params] = constraintValue.split('|');
        if (params) {
          const parsedParams = JSON.parse(params);
          return this.i18n.translate(key, {
            lang,
            args: parsedParams,
          });
        }
      },
    );
    return `${property}:${value}${formattedMessage.join(',')}`;
  }
}
